﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using OnlineFamilyCalendar.Model;

namespace OnlineFamilyCalendar.Data
{
    public class FamilyMemberRepository : IFamilyMemberRepository 
    {
        private IOnlineFamilyCalendarEntities _context;

        public FamilyMemberRepository(IOnlineFamilyCalendarEntities context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            _context = context;
        }

        public FamilyMember GetFamilyMemberByLoginname(string loginName)
        {
            return _context.FamilyMember.Include("LoginInformation")
                .Where(f => f.LoginInformation.LoginName == loginName && f.LoginInformation.IsLocked == false).SingleOrDefault();
        }

        public FamilyMember GetFamilyMemberByFamilyMemberId(Guid familyMemberId)
        {
            return _context.FamilyMember.Include("LoginInformation").Where(f => f.FamilyMemberId == familyMemberId).SingleOrDefault();
        }

        public void AddFamilyMember(FamilyMember familyMember)
        {
            _context.FamilyMember.AddObject(familyMember);
        }

        public void DeleteFamilyMember(FamilyMember familyMember)
        {
            bool familyMemberExists = _context.FamilyMember.Any(f => f.FamilyMemberId == familyMember.FamilyMemberId);
            if (familyMemberExists)
                _context.FamilyMember.DeleteObject(familyMember);
        }

        public LoginInformation GetLoginInformationByLoginId(Guid loginId)
        {
            return _context.LoginInformation.Where(l => l.LoginId == loginId).SingleOrDefault();
        }

        public void AddLoginInformation(LoginInformation loginInformation)
        {
            bool loginExists = _context.LoginInformation.Any(l => l.LoginName.ToLower() == loginInformation.LoginName.ToLower());
            if (loginExists)
                throw new InvalidOperationException("This LoginName is already in use");
            _context.LoginInformation.AddObject(loginInformation);
        }

        public void UpdateLoginInformation(LoginInformation loginInformation)
        {
            _context.LoginInformation.Attach(loginInformation);
        }

        public void SaveChanges()
        {
            _context.SaveChanges();
        }
    }        
}
